package com.datang.pet.common.pay;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-06-20 19:49
 * @notify
 * @version 1.0
 */

import com.datang.pet.common.utils.AccessNetwork;
import com.datang.pet.common.utils.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@RestController
public class test {
    @GetMapping("/pay")
    public Map<String, String> pay(String code) throws Exception {
        AccessNetwork wxCode = new AccessNetwork();
        //获取openId的方法
        String openId = wxCode.getUserOpenId(code);
        return senPay(openId);
    }

    @GetMapping("/callBack")
    public void payCallBack() {
    }

    public static Map<String, String> senPay(String openId) throws Exception {

        Map<String, String> paramMap = new LinkedHashMap<>();

        //小程序ID
        String appid = "wx951fbb59c45eb417";
        paramMap.put("appid", appid);

        //商品描述
        String body = "体验版会员价";
        paramMap.put("body", body);


        //商户号
        String mch_id = "1539039701";
        paramMap.put("mch_id", mch_id);


        //随机字符串
        String nonce_str = StringUtils.getId().toUpperCase();
        paramMap.put("nonce_str", nonce_str);


        //通知地址
        String notify_url = "http://25zi110846.zicp.vip/callBack";
        paramMap.put("notify_url", notify_url);

        //用户标识
        String openid = openId;
        paramMap.put("openid", openid);

        //商户订单号
        String out_trade_no = StringUtils.getId();
        paramMap.put("out_trade_no", out_trade_no);

        //终端IP
        String spbill_create_ip = "192.168.203.1";
        paramMap.put("spbill_create_ip", spbill_create_ip);

        //标价金额
        String total_fee = "1";
        paramMap.put("total_fee", total_fee);

        //交易类型
        String trade_type = "JSAPI";
        paramMap.put("trade_type", trade_type);

        //拼接参数
        String ascllOrder = createLinkString(paramMap);
        //拼接商户号密匙
        ascllOrder += "&key=qwertyuiopasdfghjklqwertyuiopasd";

        //md5加密转成大写
        String sin = DigestUtils.md5DigestAsHex(ascllOrder.getBytes()).toUpperCase();

        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
        String xml = "<xml>" + "<appid>" + appid + "</appid>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<mch_id>" + mch_id + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<notify_url>" + notify_url + "</notify_url>"
                + "<openid>" + openid + "</openid>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<total_fee>" + total_fee + "</total_fee>"
                + "<trade_type>" + trade_type + "</trade_type>"
                + "<sign>" + sin + "</sign>"
                + "</xml>";

        Map<String, String> map = doXMLParse(httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml));

        Set<String> set = map.keySet();
        for(String key:set){
            System.out.println(key+"--"+map.get(key));
        }

        Long timeStamp =System.currentTimeMillis() / 1000;
        String packages = "prepay_id=" + map.get("prepay_id");
        String stringSignTemp = "appId=" + appid + "&nonceStr=" + map.get("nonce_str") + "&package=" + packages + "&signType=MD5&timeStamp=" + timeStamp + "&key=qwertyuiopasdfghjklqwertyuiopasd";
        System.out.println(stringSignTemp);
        String twoSin = DigestUtils.md5DigestAsHex(stringSignTemp.getBytes()).toUpperCase();
        System.out.println(twoSin);
        map.put("sign", twoSin);
        map.put("timeStamp", timeStamp+"");
        map.put("package", packages);
        return map;
    }

    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        // 创建SSLContext
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static Map doXMLParse(String strxml) throws Exception {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();
        InputStream in = new ByteArrayInputStream(strxml.getBytes());
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流
        in.close();

        return m;
    }

    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String stringSignTemp = "appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111";
        String twoSin = DigestUtils.md5DigestAsHex(stringSignTemp.getBytes()).toUpperCase();
        System.out.println(twoSin);
    }
}
